<?php
// 应用公共文件

//远程爬取图片
function saveImage($path, $image_name)
{
    $ch = curl_init($path);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    $img = curl_exec($ch);
    curl_close($ch);
//$image_name就是要保存到什么路径,默认只写文件名的话保存到根目录
    $fp = fopen($image_name, 'w');//保存的文件名称用的是链接里面的名称
    fwrite($fp, $img);
    fclose($fp);
}

function uploadQiniu($url)
{
    try {
        //图片名称
        $key = time() . mt_rand(1, 99999) . '.jpg';

        //图片路径
        $filePath = root_path() . 'upload/img/' . $key;

        //创建本地文件和爬取源图片
        fopen($filePath, "a");
        saveImage($url, $filePath);

        //上传图片到七牛云
        $res = \app\facade\Qiniu::upload($filePath, 'content/' . $key);
        unlink($filePath);

        //把图片存入数据库
        $data = \app\model\Image::create([
            'header' => env('qiniu'),
            'url'    => 'content/' . $key,
            'key'    => '{<-' . $key . '->}'
        ]);

        if (!$res['status']) throw new \app\exception\ApiException([400, $res['msg']]);

        return $data->key;
    }catch (Exception $e){
        throw new \app\exception\ApiException([400, $e->getMessage()]);
    }
}
function wx_http_request($url, $params, $body="", $isPost=false, $isImage=false ) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url."?".http_build_query($params));
    if($isPost){
        if($isImage){
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: multipart/form-data;',
                    "Content-Length: ".strlen($body)
                )
            );
        }else{
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: text/plain'
                )
            );
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    }
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}